<?php

class Pic extends CI_Controller
{

	
	function __construct()
	{
	   parent::__construct();
	   $this->load->helper(array('url','form'));

	  
	}
	
	function index()
	{
	        $pics = $this->db->select('*')->get('pic_title')->result_array();
	        $imgs = $this->db->select('*,count(DISTINCT id)')->group_by('id')->get('pic')->result_array();
	        $news_pic = array();
	        foreach($pics as $pic){
	        	foreach($imgs as $img){
	        		if($pic['id']==$img['id']){
	        			$pic['image'] = $img['image'];	
	        			$news_pic[] = $pic;
	        			
	        		}
	        	}
	        }
	        $data['pics'] = $news_pic;
	        
	       $this->load->view('manage/header');
	        $this->load->view('pic/index',$data);
	        $this->load->view('manage/footer');
	        
	}
	
	function post()
	{
	   $this->load->library('form_validation');
	   $this->form_validation->set_rules('title','title','required');
	   
	   if($this->form_validation->run() == false)
	   {

	        $this->load->view('manage/header');
	        $this->load->view('pic/post');
	        $this->load->view('manage/footer');
	   }else{
	          $this->load->model('model_pic',"",TRUE);
	   	     $title_id = $this->model_pic->save_title();
	         $this->model_pic->save_pic($title_id); 
	         redirect('pic/index');

	   }
   
	}
	
	function edit()
	{
	      $this->load->library('form_validation');
		  
			   $this->form_validation->set_rules('title','title','required');
			   if($this->form_validation->run() == false){
			       $id = $this->uri->segment(3);
				   $id = intval($id);
				   $pic = $this->db->where('id',$id)->get('pic_title')->result_array();
				   $data['pic'] = $pic[0];
				   $pics = $this->db->where('id',$id)->get('pic')->result_array();
				   $data['pics'] = $pics;
				   
				   $this->load->view('manage/header');
				   $this->load->view('pic/edit',$data);
				   $this->load->view('manage/footer');
			   }else{
			       $this->load->model('model_pic');
				   $id = $this->model_pic->update_title();
				   $this->model_pic->update_pic($id);
				   redirect('pic/index');
			   }
		
	}
    function drop()
	{

		if($this->uri->segment(3))
		{
			$id = intval($this->uri->segment(3));
			$this->load->model('model_pic','',TRUE);
			$this->model_pic->del_pic($id);
			redirect('pic/index');
		}
	}
	
	function delete()
	{
	    $pid = $this->uri->segment(3);
		if($pid)
		{
		    $pid = intval($pid);
			$this->db->where('pid',$pid)->delete('pic');
			redirect('pic/index');
		}
	}
}